﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;
using OddUserManager.Model;
using OddUserManager.Service.IServices;
using OddUserManager.Web.Common;
using OddUserManager.Web.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace OddUserManager.Web.Controllers
{
    public class OddUserController : Controller
    {

        static Logger log = LogManager.GetCurrentClassLogger();
        private readonly IOddUserService _service;
        private readonly ISiteService _siteService;

        public OddUserController(IOddUserService service, ISiteService siteService)
        {
            _service = service;
            _siteService = siteService;
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetAllPageList(int startPage, int pageSize, int siteId)
        {

            JsonData data = new JsonData();
            try
            {
                OddUser param = new OddUser();
                param.SiteIds = GetSiteIds(siteId);
                PageViewCollection<OddUser> pageList = _service.SearchOddUserPages(param, startPage, pageSize, null, null);

                data.Success = true;
                data.Message = "查询成功";
                data.Data = pageList;

            }
            catch (Exception ex)
            {
                data.Success = false;
                data.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(data);
        }

        private string GetSiteIds(int siteId)
        {
            if (siteId < 1) return null;
            List<Site> list = _siteService.GetAllList().ToList();

            Dictionary<int, Dictionary<int, int>> d = new Dictionary<int, Dictionary<int, int>>();
            foreach (Site site in list)
            {
                if (site.ParentId > -1)
                {
                    if (d.ContainsKey(site.ParentId))
                    {
                        var dd = d[site.ParentId];
                        if (!dd.ContainsKey(site.Id))
                        {
                            dd[site.Id] = -1;
                        }
                    }
                    else
                    {
                        Dictionary<int, int> dd = new Dictionary<int, int>();
                        dd[site.Id] = -1;
                        d[site.ParentId] = dd;
                    }
                }
            }

            List<int> siteList = new List<int>();
            GetTreeNode(d, siteList, siteId);

            return string.Join(",", siteList);
        }

        public IActionResult GetOddUserBySiteId(int siteId)
        {
            JsonData d = new JsonData();
            d.Data = _service.GetOddUsersBySiteId(siteId);
            return Json(d);
        }


        private void GetTreeNode(Dictionary<int, Dictionary<int, int>> d, List<int> list, int id)
        {
            list.Add(id);
            if (!d.ContainsKey(id)) return;
            Dictionary<int, int> dd = d[id];
            foreach (int key in dd.Keys)
            {
                GetTreeNode(d, list, key);
            }

        }


        public IActionResult Get(int id)
        {
            JsonData d = new JsonData();
            d.Success = true;
            d.Data = _service.Get(id);
            return Json(d);
        }

        public async Task<IActionResult> Edit(OddUser dto)
        {
            JsonData d = new JsonData();
            try
            {
                OddUser oddUser = dto;
                if (dto == null)
                {
                    d.Success = false;
                    d.Message = "参数为空";
                    return Json(d);
                }

                if (dto.Account == null)
                {
                    d.Success = false;
                    d.Message = "账号不能为空";
                    return Json(d);
                }

                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (!result.Succeeded)
                {
                    d.Success = false;
                    d.Message = "用户已失效";
                    return Json(d);
                }

                var appUserId = result.Principal.Identity.Name;
                log.Info($"用户：{appUserId}执行编辑操作");


                OddUser param = null;

                if (dto.Id < 1)   // 新增
                {
                    param = new OddUser();
                    param.Account = dto.Account;
                    param.SiteId = dto.SiteId;
                    if (_service.IsExists(param))
                    {
                        d.Success = false;
                        d.Message = "同一站点不能存在相同账号";
                        return Json(d);
                    }

                    oddUser.CreateDate = DateTime.Now;
                    oddUser.CreateAppUserId = int.Parse(appUserId);
                    oddUser.SortIndex = GetSortIndex(oddUser.SiteId);
                }
                else   // 编辑
                {
                    oddUser = _service.Get(dto.Id);

                    if (oddUser.Account == null || !oddUser.Account.Equals(dto.Account))
                    {
                        oddUser.Account = dto.Account;

                        param = new OddUser();
                        param.Account = dto.Account;
                        param.SiteId = dto.SiteId;
                        if (_service.IsExists(param))
                        {
                            d.Success = false;
                            d.Message = "同一站点不能存在相同账号";
                            return Json(d);
                        }
                    }

                    oddUser.AccountBalance = dto.AccountBalance;

                    // 变换站点
                    if (dto.SiteId != oddUser.SiteId)
                    {
                        oddUser.SiteId = dto.SiteId;
                        oddUser.SortIndex = GetSortIndex(oddUser.SiteId);
                    }

                    oddUser.State = dto.State;
                    oddUser.Remark = dto.Remark;
                }

                oddUser.AccountType = (int)AccoutType.发单账号;
                oddUser.ModDate = DateTime.Now;
                oddUser.ModAppUserId = int.Parse(appUserId);

                _service.UpdateOrInsert(oddUser);
                _service.UpdateSiteSort();

                d.Success = true;
                d.Message = "编辑成功";
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(d);
        }

        private int GetSortIndex(int siteId)
        {
            List<OddUser> list = _service.GetOddUsersBySiteId(siteId);
            if (list == null || list.Count < 1) return 1;
            return list[0].SortIndex + 1;
        }

        public IActionResult EditBalance(OddUser dto)
        {
            JsonData d = new JsonData();
            try
            {
                var user = _service.GetUserById(dto.Id);
                user.AccountBalance = dto.AccountBalance;
                _service.InsertOrUpdateUser(user);
               
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;

            }
            return Json(d);
        }

        public IActionResult EditRemark(OddUser dto)
        {
            JsonData d = new JsonData();
            try
            {
                var user = _service.GetUserById(dto.Id);
                user.Remark = dto.Remark;
                _service.InsertOrUpdateUser(user);
                
            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
            }
            return Json(d);
        }

        public async Task<IActionResult> DeleteMuti(string ids)
        {
            JsonData d = new JsonData();

            try
            {

                var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                if (!result.Succeeded)
                {
                    d.Success = false;
                    d.Message = "用户已失效";
                    return Json(d);
                }
                var appUserId = result.Principal.Identity.Name;
                log.Error($"用户：{appUserId}执行删除操作，删除{ids}");

                string[] idArray = ids.Split(',');

                List<int> delIds = new List<int>();
                foreach (string id in idArray)
                {
                    delIds.Add(int.Parse(id));
                }
                _service.DeleteBatch(delIds);
                d.Success = true;
                d.Message = "删除成功";

            }
            catch (Exception ex)
            {
                d.Success = false;
                d.Message = ex.Message;
                log.Error(ex, ex.Message);
            }
            return Json(d);
        }


        public IActionResult DownloadFile(int selSiteId)
        {
            List<OddUser> list = null;
            OddUser param = new OddUser();
            param.SiteIds = GetSiteIds(selSiteId);
            list = _service.GetOddUsersByParam(param);


            StringBuilder sb = new StringBuilder();
            sb.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>");
            sb.Append("<table border='1' cellspacing='1' cellpadding = '1'><thead>");
            sb.Append("<th>序号</th><th>账号</th><th>余额</th><th>平台</th><th>备注</th></thead><tbody>");
            if (null != list && list.Count > 0)
            {
                list = list.OrderBy(p => p.Site.Name).ToList();
                for (var i = 0; i < list.Count; i++)
                {
                    var user = list[i];
                    sb.Append("<tr>");

                    sb.Append($"<td>{(i + 1)}</td>");
                    sb.Append($"<td>{user.Account}</td>");
                   
                    sb.Append($"<td>{user.AccountBalance}</td>");
                    sb.Append($"<td>{user.Site.Name}</td>");
                   
                    sb.Append($"<td>{user.Remark}</td>");
                    sb.Append("</tr>");
                }
            }
            sb.Append("</tbody></table></body></html>");

            var stream = new MemoryStream();
            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(sb.ToString(), Encoding.UTF8);
            streamWriter.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            var result = File(stream, "application/octet-stream", "file.xls");
            return result;
        }

        public IActionResult GetRedBlackData()
        {
            var users = RedBlackDataCache.Data;
            var groupList = users.GroupBy(p => p.SiteId);
            var sites = _siteService.GetAllList().OrderBy(p => p.SortValue).ToList();
            List<TreeModel> treeModels = new List<TreeModel>();

            foreach (var site in sites)
            {
                treeModels.Add(new TreeModel() { Id = "-"+site.Id , Text = site.Name, Parent = site.ParentId<0?"#":"-"+site.ParentId });
                
                // 根据站点ID获取账号列表
                var iuserList = groupList.FirstOrDefault(p => p.Key == site.Id);
                if (null == iuserList) { continue; }

                var userList = iuserList.ToList();
                userList.Sort(new OddUserCompare());

                List<Odd> filterOdd = null;
                foreach (var user in userList)
                {
                    var text = "";
                    if (null != user.OddList)
                    {
                        if (site.OddOrderType == OddOrderType.最大比赛编号)
                        {
                            if (site.Remark == "1")
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(15) >= DateTime.Now).OrderBy(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenBy(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).ToList();
                            }
                            else if (site.Remark == "2")
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(7) >= DateTime.Now).OrderBy(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenBy(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).ToList();

                            }
                            else
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(30) >= DateTime.Now).OrderBy(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenBy(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).ToList();

                            }

                            if (null!= filterOdd && filterOdd.Count < 5)
                            {
                                filterOdd = user.OddList.OrderBy(p => string.IsNullOrEmpty(p.OrderString) ? p.LotteryTime : DateTime.Parse(p.OrderString.Split(' ')[0])).ThenBy(p => string.IsNullOrEmpty(p.OrderString) ? 0 : int.Parse(p.OrderString.Split(' ')[1])).ThenBy(p => p.CreateTime).TakeLast(5).ToList();
                            }

                        }
                        else
                        {
                            if (site.Remark == "1")
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(15) >= DateTime.Now).OrderBy(p => p.CreateTime).ToList();
                            }
                            else if (site.Remark == "2")
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(7) >= DateTime.Now).OrderBy(p => p.CreateTime).ToList();

                            }
                            else
                            {
                                filterOdd = user.OddList.Where(p => p.CreateTime.AddDays(30) >= DateTime.Now).OrderBy(p => p.CreateTime).ToList();

                            }

                            if (null != filterOdd && filterOdd.Count < 5)
                            {
                                filterOdd = user.OddList.OrderBy(p => p.CreateTime).TakeLast(5).ToList();
                            }


                        }

                        if (null != filterOdd)
                        {
                            foreach (var c in filterOdd)
                            {
                                //状态小于5 说明该投注单还未开奖
                                if (c.Result == LotteryResults.未开奖)
                                {

                                    text += "<img src=\"../images/q.png\" />";

                                }
                                else
                                {
                                    //奖金大于0，说明中奖
                                    if (c.Result == LotteryResults.已中奖)
                                    {
                                        if (c.OwnPurchaseMoney >= 3000)
                                        {
                                            text += "<img src=\"../images/o.png\" />";
                                        }
                                        else
                                        {
                                            text += "<span class='red'>✓</span>";
                                        }
                                    }
                                    else
                                    {
                                        if (c.OwnPurchaseMoney >= 3000)
                                        {
                                            text += "<img src=\"../images/r.png\" />";
                                        }
                                        else
                                        {
                                            text += "<span class='green'>X</span>";
                                        }
                                    }
                                }
                            }
                        }
                       
                    }
                    treeModels.Add(new TreeModel() { Id = "" + user.Id.ToString(), Text = user.Account + "&nbsp;&nbsp;" + text, Parent = "-" + site.Id.ToString() });
                }
            }
            JsonData d = new JsonData();
            d.Data = treeModels;

            return Json(d);

        }

        public IActionResult GetAllUsers()
        {
            JsonData d = new JsonData();
            d.Data = _service.GetAllUserList();

            return Json(d);
        }


    }
}
